import cv2
import numpy as np

# 轮廓检测只能在二值化的图形中使用
img = cv2.imread("./img/color_recognize.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)

# 轮廓检测
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 标注所有轮廓点
for contour in contours:
    # arcLength通过轮廓计算周长
    # closed=True 我们要计算的是一个封闭图形的周长
    al = cv2.arcLength(contour, closed=True)
    # 利用近似法的方式获取图形的顶点数量
    result = cv2.approxPolyDP(contour, float(0.04 * al), closed=True)
    # 获取顶点的数量
    num = len(result)
    # 图形的描述
    shape_desc = "unknown"
    # 通过顶点数量判断是何种图形
    if num == 3:
        shape_desc = "triangle"
    elif num == 4:
        shape_desc = "rectangle"
    else:
        shape_desc = "circle"
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 0), thickness=2)
    cv2.putText(img, shape_desc, (x, y), 0, 1.5, color=(0, 0, 0), thickness=2)

cv2.imshow("img", img)
cv2.waitKey(0)
